#include "ETF.hpp"
#include "Stock.hpp"
namespace StockMarket
{
    void ETF::addStock(int code, std::weak_ptr<Stock> stock)
    {
        m_stock_ptr[code] = stock;
    }
    void ETF::addStock(const std::vector<PurchaseRedemptionEntry> &list)
    {
        for (auto &entry : list)
        {
            m_stocks[entry.code] = entry;
            m_quality[entry.code] = entry.quantity;

            if (entry.cash_flag == PurchaseRedemptionEntry::MUST)
            {
                m_total_price += entry.purchase_amount + entry.redemption_amount; // 申购替代金额 + 赎回替代金额
            }
            else
            {
                m_total_price += m_stock_ptr.at(entry.code).lock()->getPrice() *
                                 entry.quantity;
            }
        }
    }

    void ETF::updateIOPV(int stock, int old_price, int new_price)
    {
        m_updated_stocks.insert(stock);
        m_stock_price[stock] = new_price;
        if (m_stocks[stock].cash_flag == PurchaseRedemptionEntry::MUST)
        {
            return;
        }
        long long cha = new_price - old_price;
        m_total_price += cha * m_quality[stock];
    }

    long long ETF::getIOPV() const
    {
        if (m_updated_stocks.size() != m_stocks.size())
        {
            return -1;
        }
        else
            return divideAndRound(m_total_price, m_total_quality);
    }
} // namespace StockMarket